//
//  BBCameraView.m
//  BBTouch
//
//  Created by ben smith on 8/13/08.
//  This file is part of BBTouch.
//
//  BBTouch is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  BBTouch is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.

//  You should have received a copy of the GNU Lesser General Public License
//  along with BBTouch.  If not, see <http://www.gnu.org/licenses/>.
// 
//  Copyright 2008 Ben Britten Smith ben@benbritten.com .
//

#import "BBCameraView.h"
#import "BBDistortionMesh.h"
#import "BBDistortionMap.h"
#import "BBIndexedVertex.h"
#import "BBMeshController.h"
#import "BBConfigurationController.h"
#import "NSView+BBViewAdditions.h"



@implementation BBCameraView

- (id)initWithFrame:(NSRect)frame {
	self = [super initWithFrame:frame];
	if (self) {
		// Initialization code here.
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageUpdate:) name:@"BBRawVideoImageChange" object:nil];
	}
	return self;
}

-(void)setupMesh
{	
	self.mesh = [[BBMeshController sharedMeshController] cameraMesh];
	self.absoluteMeshContainingRect = [[BBMeshController sharedMeshController] meshFrame];
	[self setNeedsDisplay:YES];
}

-(BOOL)showMesh
{
	return [BBConfigurationController boolForSettingKey:@"BBShowCameraMesh"];
}

-(void)drawRect:(NSRect)rect
{
	[[NSColor darkGrayColor] set];
	NSRectFill(rect);
	if ([BBConfigurationController boolForSettingKey:@"BBShowRawVideoFlag"]) {
		[self drawRawVideo];
	}
	
	[super drawRect:rect];
	
	[self drawText:@"Camera View" centeredAtPoint:NSMakePoint(NSMidX([self bounds]), 10)];
}

-(void)drawRawVideo
{
	// draw the raw video image
	// inline with the rest of the coordinates
	NSSize scaleFactor = [image size];
	
	scaleFactor.width = [self bounds].size.width/scaleFactor.width;
	scaleFactor.height = [self bounds].size.height/scaleFactor.height;
	
	NSAffineTransform * scale = [NSAffineTransform transform];
	[scale scaleXBy:scaleFactor.width yBy:scaleFactor.height];
	
	// concat these transforms to the current context
	[scale concat];
	// draw the image
	[image drawAtPoint:NSMakePoint(0,0) 
						fromRect:NSZeroRect
					 operation:NSCompositeSourceOver
						fraction:1.0]; 	
	// undo the tranforms, dont want them to apply to any other drawing
	[scale invert];
	[scale concat];
}

-(void)imageUpdate:(id)notification
{
	if ([[notification object] isKindOfClass:[NSImage class]]) {
		[self setValue:[notification object] forKey:@"image"];
		// TODO: really only need to do this when the size changes, which really should be never (ie just once)
		[self setNeedsDisplay:YES];
	}
}





@end
